<?php
/**
 * Created by PhpStorm.
 * User: yellow
 * Date: 2019/6/25
 * Time: 15:22
 */

namespace app\admin\logic;

use app\admin\logic\code\ErrorCode;
use app\common\model\Practice;
use app\common\model\Log;
use app\common\model\PracticeLog;
use app\vehicle\model\Volunteer;
use app\vehicle\model\UserIntegralLog;
use app\common\model\User;
use app\common\model\Site;
use app\common\model\SiteTeam;
use app\common\model\Config;
use app\vehicle\logic\TplLogic;
class PracticeLogic extends BaseLogic
{

    private $PracticeModel;

    public function __construct()
    {
        parent::__construct();
        $this->PracticeModel = new Practice();
    }

    public function applyList($tempWhere, $nowPage){
        $where[] = ['aid', '=', $tempWhere['id']];
        $count = PracticeLog::where($where)->count();

        if ($count > 0){
            $articleList = PracticeLog::where($where)->page($nowPage, $tempWhere['limit'])->select();
            foreach($articleList as $k=>$v){
                $user = User::where('id','eq',$v['user_id'])->find();
                $articleList[$k]['nickname'] = $user['nick_name'];
                if(!$_SESSION['xm_travel']['admin_info']['site_id'] && !$_SESSION['xm_travel']['admin_info']['oid']){
                    $articleList[$k]['is_admin'] = 1;
                }else{
                    $articleList[$k]['is_admin'] = 0;
                }
                $times = 0;
                $info = Practice::where('id','eq',$v['aid'])->find();
                if($v['e_time']>0 && $v['e_time']>$v['s_time']){
                    $e_time = $v['e_time'];
                    if($v['e_time']>$info['activity_end_time']){
                        $e_time = $info['activity_end_time'];
                    }
                    $s_time = $v['s_time'];
                    if($v['s_time']<$info['activity_use_time']){
                        $s_time = $info['activity_use_time'];
                    }
                    $times = round(($e_time-$s_time)/3600);
                }
                $articleList[$k]['times'] = $times>0?$times:0;

                $articleList[$k]['is_suc'] = UserIntegralLog::where('practice_id','eq',$v['aid'])->where('user_id','eq',$v['user_id'])->count();
            }
            return ajaxArr(ErrorCode::$SUCCESS, 'success', $articleList, $count);
        } else{
            return ajaxArr(ErrorCode::$LISTNULL, '列表为空');
        }
    }

    public function getApplyInfo($data){
        $result = PracticeLog::get($data['id']);
        $practice = Practice::where('id','eq',$result['aid'])->find();
        $result['title'] = $practice['title'];
        $result['user'] = User::where('id','eq',$result['user_id'])->find();
        return $result;
    }

    public function PracticeList($tempWhere, $nowPage){
        if ($tempWhere['title']){
            $where[] = ['title', 'like', "%".$tempWhere['title']."%"];
        }
        if (is_numeric($tempWhere['status'])){
            $where[] = ['status', 'eq', $tempWhere['status']];
        }else if (is_numeric($tempWhere['sid'])){
            $where[] = ['status', 'eq', $tempWhere['sid']];
        }
//        $site_id = $_SESSION['xm_travel']['admin_info']['site_id'];
//        $site_id && $where[] = ['site_id', '=', $site_id];
//        $oid = $_SESSION['xm_travel']['admin_info']['oid'];
//        $oid && $where[] = ['oid', '=', $oid];
        $count = $this->PracticeModel->where($where)
            ->where(function ($query){
                $oid = $_SESSION['xm_travel']['admin_info']['oid'];
                $site_id = $_SESSION['xm_travel']['admin_info']['site_id'];
                if($oid){
                    $num = db('site_team')->where('oid','=',$oid)->count();
                    if($num) {
                        $allid = implode(',', db('site_team')->where('oid', '=', $oid)->column('id'));
                        $w[] = ['oid', 'in', $oid . ',' . $allid];
                    }else{
                        $w[] = ['oid','=',$oid];
                    }
                    $query->where($w);
                }else if($site_id) {
                    if (db('site')->where('sid', '=', $site_id)->count() ) {
                        $allid = implode(',', db('site')->where('sid', '=', $site_id)->column('id'));
                        $w[] = ['site_id', 'in', $site_id . ',' . $allid];
                        $query->where($w);
                    } else {
                        $w[] = ['site_id', 'eq', $site_id];
                        $query->where($w);
                    }
                }
            })
            ->count();
        if ($count > 0){
            $PracticeList = $this->PracticeModel->where($where)
                ->where(function ($query){
                    $oid = $_SESSION['xm_travel']['admin_info']['oid'];
                    $site_id = $_SESSION['xm_travel']['admin_info']['site_id'];
                    if($oid){
                        $num = db('site_team')->where('oid','=',$oid)->count();
                        if($num) {
                            $allid = implode(',', db('site_team')->where('oid', '=', $oid)->column('id'));
                            $w[] = ['oid', 'in', $oid . ',' . $allid];
                        }else{
                            $w[] = ['oid','=',$oid];
                        }
                        $query->where($w);
                    }else if($site_id) {
                        if (db('site')->where('sid', '=', $site_id)->count() ) {
                            $allid = implode(',', db('site')->where('sid', '=', $site_id)->column('id'));
                            $w[] = ['site_id', 'in', $site_id . ',' . $allid];
                            $query->where($w);
                        } else {
                            $w[] = ['site_id', 'eq', $site_id];
                            $query->where($w);
                        }
                    }
                })
                ->order('id desc')->page($nowPage, $tempWhere['limit'])->select();
            foreach($PracticeList as $k=>$v){
                if(!$v['code']){
                    $PracticeList[$k]['code'] = $this->getcode($v['id']);
                }
                if(!$v['retreat']){
                    $PracticeList[$k]['retreat'] = $this->getcodes($v['id']);
                }
                $PracticeList[$k]['activity_use_time'] = date('Y-m-d H:i',$v['activity_use_time']);
                $PracticeList[$k]['activity_end_time'] = date('Y-m-d H:i',$v['activity_end_time']);
            }
            return ajaxArr(ErrorCode::$SUCCESS, 'success', $PracticeList, $count);
        } else{
            return ajaxArr(ErrorCode::$LISTNULL, '列表为空');
        }
    }
    public function getcode($order_id){

        $APPID='wx0ddf18de26ea6f90';
        $AppSecret='9e85e33eaff1c91418f8f8506bdaaba5';
        $qrpath='qrcode'; //路径在public文件夹里面
        if(!is_dir('.'.$qrpath)){                              //  /public/qrcode/
            mkdir(iconv("GBK","UTF-8",'.'.$qrpath),0777,true);
        }
        $file = $qrpath.'/'.$order_id;
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        //获取access_token
        $access = json_decode($this->get_access_token($APPID,$AppSecret),true);
        $access_token= $access['access_token'];

        $url="https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=".$access_token;
        //传递参数，用$user_id区分每个用户生成的二维码
        $listdata=[
            'path'=>'pages/fu_zhiyin/detail?scene='.$order_id
        ];
        $listdata=json_encode($listdata);
        $result=$this->api_notice_increment($url,$listdata);
        if (!$result) {
            return false;
        }

        //查询是否存在二维码
        $list='';
        if(empty($list['qrcode'])){
            $res = file_put_contents("uploads/qrcode/".$order_id.".jpg", $result);
            //  将获取到的二维码图片流保存成图片文件
            if($res===false) return json_encode(array('status'=>0,'info'=>'生成二维码失败','res'=>$res));
            $filename="uploads/qrcode/".$order_id.".jpg";//用id编号当二维码名称
            $datafile=['qrcode'=>$filename];
            Practice::where('id','eq',$order_id)->update(['code'=>'/'.$filename]);
            return '/'.$filename;
        }else{
            return '';
        }
    }

    public function getcodes($order_id){

        $APPID='wx0ddf18de26ea6f90';
        $AppSecret='9e85e33eaff1c91418f8f8506bdaaba5';
        $qrpath='qrcode'; //路径在public文件夹里面
        if(!is_dir('.'.$qrpath)){                              //  /public/qrcode/
            mkdir(iconv("GBK","UTF-8",'.'.$qrpath),0777,true);
        }
        $file = $qrpath.'/'.$order_id;
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $fileUrl = $protocol.$_SERVER['HTTP_HOST'].$file;       //   http://XXXX/
        $savePath = '.'.$file;                                 //   /public/qrcode/

        //获取access_token
        $access = json_decode($this->get_access_token($APPID,$AppSecret),true);
        $access_token= $access['access_token'];

        $url="https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=".$access_token;

        //传递参数，用$user_id区分每个用户生成的二维码
        $listdata=[
            'path'=>'pages/fu_zhiyin/detail?retreat='.$order_id
        ];
        $listdata=json_encode($listdata);
        $result=$this->api_notice_increment($url,$listdata);
        if (!$result) {
            return false;
        }

        //查询是否存在二维码
        $list='';
        if(empty($list['qrcode'])){
            $res = file_put_contents("uploads/qrcode/retreat_".$order_id.".jpg", $result);
            //  将获取到的二维码图片流保存成图片文件
            if($res===false) return json_encode(array('status'=>0,'info'=>'生成二维码失败','res'=>$res));
            $filename="uploads/qrcode/retreat_".$order_id.".jpg";//用id编号当二维码名称
            $datafile=['qrcode'=>$filename];
            Practice::where('id','eq',$order_id)->update(['retreat'=>'/'.$filename]);
            return '/'.$filename;
        }else{
            return '';
        }
    }

    public function api_notice_increment($url, $data){
        $curl = curl_init();
        $ch = curl_init();
        $header = "Accept-Charset: utf-8";
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        //curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo = curl_exec($ch);
        if (curl_errno($ch)) {
            return false;
        }else{
            return $tmpInfo;
        }
    }
    public function get_access_token($APPID,$AppSecret){
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$APPID."&secret=".$AppSecret;
        return $data = $this->curl_get($url);
    }
    public function curl_get($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($curl);
        $err = curl_error($curl);
        curl_close($curl);
        return $data;
    }

    /**
     * 查找文章信息
     * @param $PracticeId
     * @return mixed
     */
    public function info($PracticeId){
        $info = $this->PracticeModel->get($PracticeId);
        if ($info){
            return ajaxArr(ErrorCode::$SUCCESS, 'success', $info);
        } else{
            return ajaxArr(ErrorCode::$INFONULL, '该文章不存在');
        }
    }

    public function log($id){
        return PracticeLog::get($id);
    }

    /**
     * 文章逻辑操作
     * @param $data
     * @return mixed
     */
    public function handle($data){
        $act = $data['act'];
        unset($data['act']);
        $res = false;
        if(!$data['thumb']){
            unset($data['thumb']);
        }
        $data['use_time'] && $data['use_time'] = strtotime($data['use_time']);
        $data['end_time'] && $data['end_time'] = strtotime($data['end_time']);
        $data['activity_use_time'] && $data['activity_use_time'] = strtotime($data['activity_use_time']);
        $data['activity_end_time'] && $data['activity_end_time'] = strtotime($data['activity_end_time']);
        switch ($act){
            case 'add':
                $oid = $_SESSION['xm_travel']['admin_info']['oid'];
                if($oid){
                    $data['oid'] = $oid;
                    $data['user_id'] = SiteTeam::where('id','eq',$oid)->value('user_id');
                }
                $data['content'] = htmlspecialchars($data['content']);
                $res = $this->PracticeModel->allowField(true)->save($data);
                break;
            case 'edit':
                if(!$data['remark'] && $data['status']==2){
                    return ajaxArr(ErrorCode::$OPERATIONERROR, '请输入审核意见');
                }
                $info = $this->PracticeModel->where('id',$data['id'])->find();
                $openid = User::where('id','eq',$info['user_id'])->value('open_id');
                if($data['status']==1){
                    //$openid && TplLogic::examineTpl($openid,'活动发布','审核通过');
                    $openid && TplLogic::examineStatus($openid,'审核通过','该内容已审核通过');
                }else if($data['status']==2){
                    //$openid && TplLogic::examineTpl($openid,'活动发布',$data['remark']);
                    $openid && TplLogic::examineStatus($openid,'审核不通过',$data['remark']);
                }
                $res = $this->PracticeModel->allowField(true)->save($data, $data['id']);
                break;
            case 'sub_info':
                $res = $this->PracticeModel->allowField(true)->save($data, $data['id']);
                break;
            case 'del':
                $Practice = $this->PracticeModel->get($data['id']);
                $res = $Practice->delete();
                break;
            case 'batch':
                $res = $this->PracticeModel->where('id','in',$data['ids'])->delete();
                break;
            default:
                break;
        }
        if ($res){
            return ajaxArr(ErrorCode::$SUCCESS, '操作成功');
        } else{
            return ajaxArr(ErrorCode::$OPERATIONERROR, '操作失败');
        }
    }

    public function end_tpl($id){
        $list = Practice::where('id','eq',$id)->select();
        foreach($list as $k=>$v) {
            $num = UserIntegralLog::where('practice_id','eq',$v['id'])->count();
            if(!$num) {
                $openid = User::where('id', 'eq', $v['user_id'])->value('open_id');
                $openid && TplLogic::endActivityTpl($openid, $v['title'], $v['id']);
                Practice::where('id', 'eq', $v['id'])->update(['is_up' => 1]);
                PracticeLog::where('aid', 'eq', $v['id'])->update(['status' => 2]);
                $log_list = PracticeLog::where('aid', 'eq', $v['id'])->select();
                foreach ($log_list as $kk => $vv) {
                    $nums = UserIntegralLog::where('user_id','eq',$vv['user_id'])->where('practice_id','eq',$v['id'])->count();
                    if(!$nums) {
                        $t = round(($vv['e_time'] - $vv['s_time']) / 3600);
                        if($t>0) {
                            if ($vv['volunteer'] == 1) {
                                $duration = Config::where('key', 'eq', 'duration1')->value('value') ?? 1;
                                User::where('id', 'eq', $vv['user_id'])->setInc('duration', $t);
                                $integral = intval($t * $duration);
                                $insert['user_id'] = $vv['user_id'];
                                $insert['integral'] = $integral;
                                $insert['create_time'] = time();
                                $insert['remark'] = '服务时长赠送';
                                $insert['practice_id'] = $vv['aid'];
                                $integral > 0 && UserIntegralLog::insert($insert);
                            } else {
                                $duration = Config::where('key', 'eq', 'duration2')->value('value') ?? 1;
                                User::where('id', 'eq', $vv['user_id'])->setInc('duration1', $t);
                                $integral = intval($t * $duration);
                                $insert['user_id'] = $vv['user_id'];
                                $insert['integral'] = $integral;
                                $insert['create_time'] = time();
                                $insert['remark'] = '活动时长赠送';
                                $insert['practice_id'] = $vv['aid'];
                                $integral > 0 && UserIntegralLog::insert($insert);
                            }
                            User::where('id', 'eq', $vv['user_id'])->setInc('integral', $integral);
                        }
                    }
                }
            }
        }
    }

    public function sendApply($data){
        $log = PracticeLog::where('id', 'eq', $data['id'])->find();
        $nums = UserIntegralLog::where('user_id','eq',$log['user_id'])->where('practice_id','eq',$log['aid'])->count();
        if(!$nums) {
            PracticeLog::where('id', 'eq', $data['id'])->update(['is_send'=>1,'send_time'=>$data['send_time']]);
            $t = $data['send_time'];
            if($t>0) {
                if ($log['volunteer'] == 1) {
                    $duration = Config::where('key', 'eq', 'duration1')->value('value') ?? 1;
                    User::where('id', 'eq', $log['user_id'])->setInc('duration', $t);
                    $integral = intval($t * $duration);
                    $insert['user_id'] = $log['user_id'];
                    $insert['integral'] = $integral;
                    $insert['create_time'] = time();
                    $insert['remark'] = '服务时长赠送';
                    $insert['practice_id'] = $log['aid'];
                    $integral > 0 && UserIntegralLog::insert($insert);
                } else {
                    $duration = Config::where('key', 'eq', 'duration2')->value('value') ?? 1;
                    User::where('id', 'eq', $log['user_id'])->setInc('duration1', $t);
                    $integral = intval($t * $duration);
                    $insert['user_id'] = $log['user_id'];
                    $insert['integral'] = $integral;
                    $insert['create_time'] = time();
                    $insert['remark'] = '活动时长赠送';
                    $insert['practice_id'] = $log['aid'];
                    $integral > 0 && UserIntegralLog::insert($insert);
                }
                User::where('id', 'eq', $log['user_id'])->setInc('integral', $integral);
                return ajaxArr(ErrorCode::$SUCCESS, '操作成功');
            }else{
                return ajaxArr(ErrorCode::$OPERATIONERROR, '操作失败');
            }
        }else{
            return ajaxArr(ErrorCode::$OPERATIONERROR, '操作失败');
        }
    }

    public function handles($data){
        $act = $data['act'];
        unset($data['act']);
        $res = false;
        if(!$data['thumb']){
            unset($data['thumb']);
        }
        $data['use_time'] = strtotime($data['use_time']);
        $data['end_time'] = strtotime($data['end_time']);

        switch ($act){
            case 'add':
                $data['content'] = htmlspecialchars($data['content']);
                $res = $this->PracticeModel->allowField(true)->save($data);
                break;
            case 'edit':
                $info = PracticeLog::where('id','eq',$data['id'])->find();
                $up['status'] = $data['status'];
                if($up['status']==1){
                    $up['s_time'] = time();
                }else if($up['status']==2){
                    $up['c_time'] = time();
//                    $t = ceil(($up['c_time']-$info['s_time'])/3600);
//                    if($info['status']==1) {
//                        if ($info['volunteer'] == 1) {
//                            $duration = Config::where('key','eq','duration1')->value('value')??1;
//                            User::where('id', 'eq', $info['user_id'])->setInc('duration', $t);
//                            $integral = intval($t * $duration);
//                            $insert['user_id'] = $info['user_id'];
//                            $insert['integral'] = $integral;
//                            $insert['create_time'] = time();
//                            $insert['remark'] = '服务时长赠送';
//                            $integral>0 && UserIntegralLog::insert($insert);
//                        } else {
//                            $duration = Config::where('key','eq','duration2')->value('value')??1;
//                            User::where('id', 'eq', $info['user_id'])->setInc('duration1', $t);
//                            $integral = intval($t*$duration);
//                            $insert['user_id'] = $info['user_id'];
//                            $insert['integral'] = $integral;
//                            $insert['create_time'] = time();
//                            $insert['remark'] = '活动时长赠送';
//                            $integral>0 && UserIntegralLog::insert($insert);
//                        }
//                        User::where('id', 'eq', $info['user_id'])->setInc('integral', $integral);
//                    }
                }
                PracticeLog::where('id','eq',$data['id'])->update($up);
                $res = true;
                break;
            case 'del':
                $Practice = $this->PracticeModel->get($data['id']);
                $res = $Practice->delete();
                break;
            default:
                break;
        }
        if ($res){
            return ajaxArr(ErrorCode::$SUCCESS, '操作成功');
        } else{
            return ajaxArr(ErrorCode::$OPERATIONERROR, '操作失败');
        }
    }

    public function applySuccess($data){
        $act = $data['act'];
        unset($data['act']);
        $res = false;
        switch ($act){
            case 'edit':
                if(!isset($data['is_end'])){
                    return ajaxArr(ErrorCode::$OPERATIONERROR, '操作失败');
                }
                $practice = $this->PracticeModel->where('id','eq',$data['id'])->find();
                if(!$practice['report_contents']){
                    return ajaxArr(ErrorCode::$OPERATIONERROR, '内容未上报无法审核');
                }
                if($data['is_end']==1 && !$practice['e_time']){
                    if ($practice['site_id']) {
                        Site::where('id', 'eq', $practice['site_id'])->setInc('number');
                    }
                    if ($practice['oid']) {
                        SiteTeam::where('id', 'eq', $practice['oid'])->setInc('number');
                    }
                }
                if($data['is_end']==1){
                    //$this->end_tpl($practice['id']);
                }
                Log::insert(['aid'=>$data['id'],'create_time'=>time(),'content'=>$data['is_end']]);
                $res = $this->PracticeModel->where('id','eq',$data['id'])->update(['is_end'=>$data['is_end'],'e_time'=>time()]);
                break;
            default:
                break;
        }
        if ($res){
            return ajaxArr(ErrorCode::$SUCCESS, '操作成功');
        } else{
            return ajaxArr(ErrorCode::$OPERATIONERROR, '操作失败');
        }
    }
}